const express = require('express');
const router = express.Router();
const passport = require('passport');

const Message = require('../../models/message');


router.get('/test', (req, res) => {
  res.json({
    msg: 'message works'
  });
});


// @route  POST api/messages/add
// @desc   创建信息接口
// @access Private
router.post(
  '/add',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    const messageFields = {};

    if (req.body.name) messageFields.name = req.body.name;
    if (req.body.describe) messageFields.describe = req.body.describe;

    new Message(messageFields).save().then(message => {
      res.json(message);
    });
  }
);

// @route  GET api/message
// @desc   获取所有信息
// @access Private

router.get(
  '/',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    Message.find().sort({
        date: -1
      })
      .then(message => {
        if (!message) {
          return res.status(404).json('没有任何内容');
        }

        res.json(message);
      })
      .catch(err => res.status(404).json(err));
  }
);



module.exports = router;